<?php
namespace adminmatrix\admin\annotation;

use ReflectionObject;
use ReflectionClass;
use adminmatrix\admin\annotation\Loggable;
use adminmatrix\admin\request\LoggableRequest;
use think\Request;

trait InteractsWithLoggable
{
    protected function autoLoggable()
    {
        // 绑定 LoggableRequest 到容器
        $this->app->bind('request', LoggableRequest::class);
        
        // 在请求开始时处理注解
        $this->app->event->listen('HttpRun', function() {
            $this->processLoggableAnnotations();
        });

        // 立即处理当前对象的注解
        $this->processLoggableAnnotations();
    }

    protected function processLoggableAnnotations()
    {
        $object = $this;
        if ($this->isInjectClass(get_class($object))) {
            $refClass = new ReflectionClass($object);
            
            
            // 获取方法上的注解
            foreach ($refClass->getMethods() as $method) {
                $methodAttrs = $method->getAttributes(Loggable::class);
                if (!empty($methodAttrs)) {
                    foreach ($methodAttrs as $attr) {
                        $loggable = $attr->newInstance();
                        $loggable->ref = $method;

                        
                        // 使用 LoggableRequest
                        /** @var LoggableRequest $request */
                        $request = $this->app->request;
                        $request->loggable($loggable);
                        
   
                    }
                }
            }
        }
    }
}
